package com.dragon.concurrent.demo.waitnotify;

public class ProduceConsumeVersion2 {

    private int i = 0;

    private final Object LOCK = new Object();

    // 是否已经生产了
    private volatile boolean isProduced = false;

    public void produce() {
        synchronized (LOCK) {
            if (isProduced) {
                try {
                    LOCK.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                System.out.println("P->" + (++i));
                isProduced = true;
                LOCK.notify();
            }
        }
    }

    public void consume() {
        synchronized (LOCK) {
            if (isProduced) {
                System.out.println("C->" + i);
                isProduced = false;
                LOCK.notify();
            } else {
                try {
                    LOCK.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        ProduceConsumeVersion2 produceConsumeVersion2 = new ProduceConsumeVersion2();
        new Thread(() -> {
            while (true) {
                produceConsumeVersion2.produce();
            }
        }).start();

        new Thread(() -> {
            while (true) {
                produceConsumeVersion2.consume();
            }
        }).start();
    }
}
